package api

import (
	"context"
	"encoding/binary"
	"fmt"
	"github.com/gorilla/websocket"
	"io"
	"myproject/backend/utils"
	"net/http"
	"os"
	"path/filepath"
	"sync"
	"time"
)

type CameraClient struct {
	Conn        *websocket.Conn
	ConnActive  bool
	cameraLock  sync.Mutex
	isCapturing bool
	pathIndex   int
	ctx         context.Context
	cancel      context.CancelFunc
	writeChan   chan []byte
	closeOnce   sync.Once
	CameraID    int
	CameraType  string
}

func (c *CameraClient) CapturePicture(filename string, data []byte) error {
	desktopPath, err := utils.GetDesktopPath()
	if err != nil {
		return err
	}
	fmt.Printf("[DEBUG] 桌面路径: %s\n", desktopPath)
	targetPath := filepath.Join(desktopPath, "captures")
	fmt.Printf("[DEBUG] 目标路径: %s\n", targetPath)
	if _, err := os.Stat(targetPath); os.IsNotExist(err) {
		fmt.Printf("[INFO] 目录不存在，正在创建: %s\n", targetPath)
		if err := os.MkdirAll(targetPath, 0755); err != nil {
			return fmt.Errorf("创建目录失败: %v (目标路径: %s)", err, targetPath)
		}
	} else if err != nil {
		return fmt.Errorf("检查目录状态失败: %v", err)
	}
	fullPath := filepath.Join(targetPath, filename)
	if err := os.WriteFile(fullPath, data, 0644); err != nil {
		return fmt.Errorf("写入文件失败: %v (路径: %s)", err, fullPath)
	}
	fmt.Printf("[SUCCESS] 截图已保存: %s\n", fullPath)
	return nil
}

type VideoStreamClient struct {
	videoFeedURL string
	httpClient   *http.Client
}

var cameraIndexDict = map[int]int{
	1: 1, // 第一个摄像头在中间
	2: 2, // 第二个摄像头中左
	3: 3, // 第三个摄像头中右
	4: 4, // 第四个摄像头左边
	5: 5, // 第五个摄像头右边
}

func NewVideoStreamClient(pythonServiceURL string, cameraID int) *VideoStreamClient {
	apiCameraID := cameraIndexDict[cameraID]
	url := fmt.Sprintf("%s/video_feed/%d", pythonServiceURL, apiCameraID)
	fmt.Printf("[DEBUG] 视频流地址: %s\n", url)
	return &VideoStreamClient{
		videoFeedURL: url,
		httpClient:   &http.Client{},
	}
}

func NewVideoTipsClient(pythonServiceURL string) *VideoStreamClient {
	url := fmt.Sprintf("%s/tips", pythonServiceURL)
	fmt.Printf("[DEBUG] 视频流地址地址: %s\n", url)
	return &VideoStreamClient{
		videoFeedURL: url,
		httpClient:   &http.Client{},
	}
}

func (c *VideoStreamClient) GetVideoStream() (io.ReadCloser, error) {
	resp, err := c.httpClient.Get(c.videoFeedURL)
	if err != nil {
		return nil, err
	}
	return resp.Body, nil
}

func (c *CameraClient) sendFrame(jpegData []byte) error {
	if err := c.Conn.SetWriteDeadline(time.Now().Add(3 * time.Second)); err != nil {
		return err
	}
	// 1. 计算 JPEG 数据长度，转为 4 字节（小端）
	length := uint32(len(jpegData))
	lengthBuf := make([]byte, 4)
	binary.LittleEndian.PutUint32(lengthBuf, length) // 用小端存储长度
	// 2. 拼接：长度前缀 + JPEG 数据
	frame := append(lengthBuf, jpegData...)
	// 3. 发送二进制帧（单帧发送，无需分两次）
	return c.Conn.WriteMessage(websocket.BinaryMessage, frame)
}
